/* $Id: RequestStorageModel.java 104 2011-01-19 18:47:00Z altdotua@gmail.com $ */

package alt.djudge.frontend.server.models;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestStorageModel
{
	public static void saveData(String key, String value, HttpServletRequest request, HttpServletResponse response)
	{
		Cookie cookie = new Cookie(key, value);
		cookie.setMaxAge(60 * 24 * 60 * 365);
		response.addCookie(cookie);
	}

	public static void saveData(String key, String value, HttpServletRequest request, HttpServletResponse response, boolean useSessionNotCookies)
	{
		if (!useSessionNotCookies)
		{
    		Cookie cookie = new Cookie(key, value);
    		cookie.setMaxAge(60 * 24 * 60 * 365);
    		response.addCookie(cookie);
		}
		else
		{
			request.getSession().setAttribute(key, value);
		}
	}

	public static String getData(String key, HttpServletRequest request)
	{
		// session has higher priority than cookies 
		Object sessionData = request.getSession().getAttribute(key);
		if (sessionData != null && sessionData.toString().length() != 0)
			return sessionData.toString();
		
		if (request.getCookies() != null)
		{
    		for (Cookie cookie : request.getCookies())
    		{
    			if (cookie.getName().equals(key))
    				return cookie.getValue();
    		}
		}
		return null;
	}

	public static void deleteData(String key, HttpServletRequest request, HttpServletResponse response)
	{
		request.getSession().setAttribute(key, "");
		Cookie cookie = new Cookie(key, "");
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}
	
}
